﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WebSocketClientApp
{
    public partial class Form1 : Form
    {
        private WebSocketClient _client;
        public Form1()
        {
            InitializeComponent();
            _client = new WebSocketClient();
        }

        private async void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                await _client.DisconnectAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private async void btn_connect_Click(object sender, EventArgs e)
        {
            try
            {
                await _client.ConnectAsync();
                MessageBox.Show("WebSocket 客户端已连接！");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"连接失败：{ex.Message}");
            }
        }

        private async void btn_send_Click(object sender, EventArgs e)
        {
            try
            {
                string message = txt_send.Text;
                try
                {
                    await _client.SendMessageAsync(message);
                    MessageBox.Show("消息已发送！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发送失败：{ex.Message}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private async void btn_receive_Click(object sender, EventArgs e)
        {
            try
            {
                try
                {
                    await _client.ReceiveMessageAsync();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"接收失败：{ex.Message}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}
